/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessions;

import entities.Genre;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@Stateless
@LocalBean
public class GenreManager {
    @PersistenceContext(unitName = "ProjetStreamingBoulinguezCheng-ejbPU")
    private EntityManager em;

    public Genre createGenre(String label) {
        Genre genre = getGenre(label);
        
        // If doesn't exist, create
        if(genre == null && !label.equals("")) {
            genre = new Genre(label);
            persist(genre);
        }
        
        return genre;
    }
    
    // Get all genres
    public List<Genre> getAllGenres() {
        Query query = em.createNamedQuery("Genre.findAll");
        return query.getResultList();
    }
    
    // Get an album with it id
    public Genre getGenre(Long id) {
        Query query = em.createNamedQuery("Genre.findById");
        query.setParameter("id", id);

        try {
            Object result = query.getSingleResult();
            return (Genre) result;
        } catch (NoResultException e) {
            return null;
        }
    }
    
    // Get an album with it label
    public Genre getGenre(String label) {
        Query query = em.createNamedQuery("Genre.findByLabel");
        query.setParameter("label", label);

        try {
            Object result = query.getSingleResult();
            return (Genre) result;
        } catch (NoResultException e) {
            return null;
        }
    }
    
    public void persist(Object object) {
        em.persist(object);
    }

}
